let dataDefer = Promise.resolve()

// 读取内容
function readData (name) {
  return dataDefer = dataDefer.then(() => {
    return new Promise((resolve, reject) => {
      plus.io.requestFileSystem( plus.io.PRIVATE_DOC, function( fs ) {
        // fs.root是根目录操作对象DirectoryEntry
        // console.log("url="+fs.toURL())
        const fileName = name ? name + '.txt' : 'db.txt'
        fs.root.getFile(fileName, { create: true }, function(fileEntry) {
          fileEntry.file( function(file){
            // console.log(file.size + '--' + file.name)
            var fileReader = new plus.io.FileReader()
            // console.log("getFile:" + JSON.stringify(file))
            fileReader.readAsText(file, 'utf-8')
            fileReader.onloadend = function(evt) {
              let data = ''
              var result = evt.target.result
              if(result !== '' && /\{|\[/.test(result)) {
                try {
                  let json = JSON.parse(result)
                  data = json
                } catch (e) {
                  data = result
                }
              }
              resolve({ state: 1, message:"读取成功！", data: data })
            }
            fileReader.onloaderror = function(evt) {
              reject({ state: -1, message: e.message })
            }
          })
        }, function ( e ) {
          reject({ state: -1, message: e.message })
        })
      }, function ( e ) {
        reject({ state: -1, message: e.message })
      })
    })
  })
}

// 写入内容
function writeData (data, name) {
  return dataDefer = dataDefer.then(() => {
    return new Promise((resolve, reject) => {
      plus.io.requestFileSystem( plus.io.PRIVATE_DOC, function(fs) {
        // fs.root是根目录操作对象DirectoryEntry
        // console.log("url="+fs.toURL());
        const fileName = name ? name + '.txt' : 'db.txt'
        fs.root.getFile(fileName, { create: true }, function(fileEntry) {
          fileEntry.createWriter( function ( writer ) {
            writer.onwrite = function (e) {
              console.log( 'Write data success!' )
            }
            data = typeof data === 'object' ? JSON.stringify(data, null, '  ') : String(data)
            writer.seek(0)
            // var bb = new BlobBuilder()
            // bb.append(data)
            // writer.write(bb.getBlob('text/plain'))
            writer.write(data)
            resolve({state: 1, message: '保存数据成功！'})
          }, function (e) {
            reject({ state: -1, message: e.message })
          })
        }, function ( e ) {
          reject({ state: -1, message: e.message })
        })
      }, function (e) {
        reject({ state: -1, message: e.message })
      })
    })
  })
}

// 清空内容
function clearData (name) {
  return dataDefer = dataDefer.then(() => {
    return writeData('', name)
  })
}

export default {
  readData,
  writeData,
  clearData
}

export {
  readData,
  writeData,
  clearData
}
